package com.example.iorder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;

import com.example.iorder.util.AnimationHandler;
import com.example.iorder.util.NavigationManager;

public class SearchRestaurant extends Activity {
	private boolean advancedSearchCollapsed = false;
	private View advancedSearchView = null;
	private int screenHeight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_restaurant);
		
		// Make some last layout changes after everything is loaded
		determineScreenHeight();
		final RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.searchScreen);
		ViewTreeObserver vto = mainLayout.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
		    @SuppressWarnings("deprecation")
			@Override 
		    public void onGlobalLayout() {
		    	configureSearchButton();
		    	configureSearchBox();
		        mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
		    } 
		});
		
		// Add the header navigation
		NavigationManager.addHeaderNavigation(this, mainLayout);
		NavigationManager.setCurrentTab(this, NavigationManager.TabButtons.Search);
	}
	
	protected void onResume() {
		super.onResume();
		NavigationManager.setCurrentTab(this, NavigationManager.TabButtons.Search);
	}

	public void showAdvancedSearch(View view) {
		Button aSearchButton = (Button) findViewById(R.id.advancedSearch);
		// If not collapsed, then add the view. Otherwise, remove it 
		if (!advancedSearchCollapsed) {
			LayoutInflater inflater = LayoutInflater.from(this);
			advancedSearchView = inflater.inflate(R.layout.advanced_search,	null);
			setImageForAdvancedSearchButton(aSearchButton, true);

			RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.searchScreen_inner);
			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.addRule(RelativeLayout.BELOW, aSearchButton.getId());
			parentLayout.addView(advancedSearchView, lp);
			AnimationHandler.expandView(this, advancedSearchView);

			advancedSearchCollapsed = true;
		} else {
			RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.searchScreen_inner);
			setImageForAdvancedSearchButton(aSearchButton, false);
			AnimationHandler.collapseView(this, advancedSearchView);
			parentLayout.removeView(advancedSearchView);
			
			advancedSearchCollapsed = false;
		}
	}

	public void searchRestaurants(View view) {
		// Get the (extra) search parameters
		EditText searchBox = (EditText) findViewById(R.id.searchValue);
		String searchByName = searchBox.getText().toString();
		String searchByCity = "";
		if (advancedSearchCollapsed) {
			Spinner citySpinner = (Spinner) findViewById(R.id.searchCity);
			String selectedCity = citySpinner.getSelectedItem().toString();
			String allCitiesString = getResources().getString(R.string.all);
			if (!selectedCity.equals(allCitiesString))
				searchByCity = selectedCity;
		}

		// Send the request and start the next activity
		Intent searchForRestaurants = new Intent(SearchRestaurant.this,	SearchResultsRestaurant.class);
		searchForRestaurants.putExtra("restName", searchByName);
		searchForRestaurants.putExtra("restCity", searchByCity);
		startActivity(searchForRestaurants);
		//AnimationHandler.addSlideRightToLeftAnim(this);
	}
	
	public void clearTextOfEditText(View view) {
		EditText textBox = (EditText) findViewById(R.id.searchValue);
		textBox.setText("");
		textBox.requestFocus();
	}

	private void setImageForAdvancedSearchButton(Button advSearchButton, boolean collapsed) {
		Drawable image = null;
		if (collapsed) {
			image = getResources().getDrawable(R.drawable.arrow_up);
		} else {
			image = getResources().getDrawable(R.drawable.arrow_down);
		}

		if (image != null) {
			advSearchButton.setCompoundDrawablesWithIntrinsicBounds(null, null, image, null);
		}
	}
	
	private void configureSearchButton() {
		ImageButton searchButton = (ImageButton) findViewById(R.id.btnSearchRest);
		int topMarginToAdd = getMiddlePointOfScreen(searchButton);
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.setMargins(5, topMarginToAdd, 0, 0);
		params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		searchButton.setLayoutParams(params);
	}
	
	private void configureSearchBox() {
		final EditText textBox = (EditText) findViewById(R.id.searchValue);
		textBox.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// if enter is pressed start calculating
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
					String text = ((EditText) v).getText().toString();
					// find how many rows it cointains
					int editTextRowCount = text.split("\\n").length;
					// user has input more than limited - lets do something
					// about that
					if (editTextRowCount >= 1) {
						// find the last break
						int lastBreakIndex = text.lastIndexOf("\n");
						// compose new text
						String newText = text.substring(0, lastBreakIndex);
						// add new text - delete old one and append new one
						// (append because I want the cursor to be at the end)
						((EditText) v).setText("");
						((EditText) v).append(newText);
					}
				}
				return false;
			}
		});
		
		ImageButton searchButton = (ImageButton) findViewById(R.id.btnSearchRest);
		int topMarginToAdd = getMiddlePointOfScreen(searchButton);
		
		final ImageButton textClearButton = (ImageButton) findViewById(R.id.clearText);
		LayoutParams params2 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params2.addRule(RelativeLayout.ALIGN_RIGHT, textBox.getId());
		params2.setMargins(0, topMarginToAdd + 4, 0, 0);
		textClearButton.setLayoutParams(params2);
		
		int topMarginToAddTextBox = topMarginToAdd - searchButton.getHeight() / 15;
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		params.setMargins(0, topMarginToAddTextBox, 0, 0);
		params.addRule(RelativeLayout.LEFT_OF, searchButton.getId());
		textBox.setLayoutParams(params);
		
		textBox.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					textClearButton.setVisibility(View.VISIBLE);
				}
				return false;
			}
		});
	}
	
	private int getMiddlePointOfScreen(View viewInMiddle) {
		int viewHeight = viewInMiddle.getHeight();
		int middlePoint = screenHeight / 2 - viewHeight * 2;
		return middlePoint;
	}
	
	@SuppressWarnings("deprecation")
	private void determineScreenHeight() {
		Display display = getWindowManager().getDefaultDisplay();
		screenHeight = display.getHeight();
	}
}
